<?php

namespace app\common\job;

use app\common\model\Transfer;
use app\common\model\TransferBatch;
use app\common\service\TransfersServer;
use app\common\traits\JobRetryTraits;
use app\index\traits\PaymentTrait;
use think\queue\Job;

/**
 * 批量转账重试
 * Class TransferBatchRetry
 * @package app\common\job
 */
class TransferBatchRetry
{
    use PaymentTrait;
    use JobRetryTraits;

    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        $id = $data['id'] ?? null;

        if (!is_id($id)) {
            $job->delete();
            return;
        }

        $result = $this->getTransfersServer()->retryBatchTransfer($id);
        if (!$result) {
            $this->retryUntilMaxAttempts($job, 20, fn($attempts) => pow(min($attempts, 4), 2) * 1200 + mt_rand(0, 1200), '消费队列：批量转账发起重试次数达到最大 ID=' . $id);
            return;
        }

        $job->delete();
    }

    private function getTransfersServer(): TransfersServer
    {
        return app(TransfersServer::class);
    }
}
